import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;


import java.io.IOException;
import java.util.Scanner;


public class MatrixReadSave 
{
	private final static int defaultLenght = 2;
	
	public static boolean saveMatrixInTextFile(int[][] matrix, String fileName)
	{
		try 
		{
			FileOutputStream fos = new FileOutputStream(fileName + ".txt");
			DataOutputStream writer = new DataOutputStream(fos);
			
			writer.writeUTF((String.valueOf(matrix.length + "\n")));
			writer.writeUTF((String.valueOf(matrix[0].length + "\n")));
			
			for (int i = 0; i < matrix.length; i++) 
			{
				for (int j = 0; j < matrix[i].length; j++) 
				{
					int test = matrix[i][j];
					
					writer.writeUTF((String.valueOf(test)));
					writer.writeChar(' ');
				}
				writer.writeChars("\n");
			}
			writer.flush();
			writer.close();
			
		} catch (IOException e) 
		{
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	

	public static int[][] loadMatrixFromTextFile(String fileName) 
	{
		int[][] numberArray = new int[defaultLenght][defaultLenght];
		
		try 
		{	
			FileReader input = new FileReader(fileName);
			BufferedReader br = new BufferedReader(input);
			
			String strLine;
			int counterRows = 0;
			while ((strLine = br.readLine()) != null)  
			{
				if (counterRows >= numberArray.length)
					extendArray(numberArray);
				
				
				int counterSpalten = 0;
				String[] temp = strLine.trim().split(" ");
				for (int i = 0; i < temp.length -1; i++)
				{
					if (counterSpalten >= numberArray[0].length)
						extendArray(numberArray);
					
					numberArray[counterRows][counterSpalten] = Integer.parseInt(temp[i].getBytes().toString());
					counterSpalten++;
				}
				counterRows++;
			}
			input.close();
			
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		
		return numberArray;
	}
	
	static void matrixMultiply(int[][] matrixA, int[][] matrixB, int[][] matrixC)
	{
		int rowLengthMatrixA = matrixA.length;
		int spaltenLengthMatrixA = matrixA[0].length;
		
		
		int counterA = 0, counterB = 0;
		// Spalten der zweiten Matrix durchlaufen
		for (int j2 = 0; j2 < matrixB.length; j2++) 
		{
			int value = 0;
			
			//Zeilen der zweiten Matrix durchlaufen
			for (int k = 0; k < matrixB.length; k++) 
			{
				value = matrixA[counterA][counterB] * matrixB[j2][k];
				counterB++;
			}
			
			matrixC[counterA][j2] = value;
		}
		
		
		
	}
	
	private static int[][] extendArray(int[][] matrix)
	{
		int[][] tempMatrix = new int[matrix.length *2][matrix[0].length *2];
		
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix[0].length; j++) {
				tempMatrix[i][j] = matrix[i][j];
			}
		}
		
		return tempMatrix;
	}
}
